
const exec = require("../db/index")
const jwt = require('jsonwebtoken');


const moment = require("moment")

const { setTokenOptions } = require("../utils/config")

const md5 = require("md5")
const request = require("request")

const { formatToJson, createUID } = require("../utils/index")
const {
    WECHAT_APPID, WECHAT_SECRER, WECHAT_REDIRECT,
    ERROR_GETTING_USER_INFO, SUCCESS_GETTING_INFO,
    ERROR_ACCOUNT_NOT_EXIST, ERROR_ACCOUNT_DISABLED,
    ERROR_PERMISSION_INSUFFICIENT

} = require("../utils/constant")



let wxUse = {
    code: '',// 小程序传过来的code
    encryptedData: '',
    iv: '',
    userInfo: '',
    secret: '',
    grant_type: 'authorization_code', // 授权(必填)默认值
}


// 注册
exports.useRegister = async (req, res) => {
    let { phone, username, password, againPwd, type } = req.body
    const sql = `select username from users where username = ?`;
    if (password !== againPwd) return res.output("两次密码不一致", -1)
    try {
        const result = await exec(sql, [username])
        if (result.length > 0) return res.output("用户名已存在", -1)

        // 检验手机号码是否重复
        const isHasPhone = `select phone from users where phone = ?`;
        const vaidPhone = await exec(isHasPhone, [phone])
        if (vaidPhone.length > 0) return res.output("当前手机手机号已存在", -1)

        // 密码加密
        password = md5(password)
        // 生成uid
        const u_id = createUID()

        const sql2 = `insert into users (u_id,phone,username,password,type,register_Time,update_time) VALUES (?,?,?,?,?,?,?)`;
        const result2 = await exec(sql2, [u_id, phone, username, password, type, moment().format("YYYY-MM-DD HH:mm:ss"), moment().format("YYYY-MM-DD HH:mm:ss")])
        if (result2.affectedRows !== 1) return res.output("注册失败", -1)
        res.output("注册成功", 0)

    } catch (error) {
        return res.output(error)
    }
}

// 登录
// 豆包生成的代码


exports.useLogin = async (req, res) => {
    // 获取客户端发送过来的数据，添加默认值以防属性不存在
    const { username = '', password = '', type = '' } = req.body;
    const encryptedPassword = md5(password);

    // 使用参数化查询进行数据库操作，避免SQL注入并优化密码验证逻辑
    const sql = `select u_id from users where username=? and type=? and status = 1 and password =?`;
    const result = await exec(sql, [username, type, encryptedPassword]);
    if (result.length < 1) return res.output(ERROR_ACCOUNT_NOT_EXIST.message, ERROR_ACCOUNT_NOT_EXIST.code);
    if (result[0].status == 0) return res.output(ERROR_ACCOUNT_DISABLED.message, ERROR_ACCOUNT_DISABLED.code);

    const user = { username };

    const token = jwt.sign(user, setTokenOptions.jwtSecretKey, { expiresIn: setTokenOptions.expiresIn });
    // 语句执行成功，直接返回相关信息，无需多余的密码比较操作（已在数据库查询时验证）
    res.output("登录成功", 0, { token: token, u_id: result[0].u_id });
}



// // 获取用户信息


// 豆包生成代码


exports.getUserInfo = async (req, res) => {
    // 使用驼峰命名法规范变量名
    let { u_id } = req.query;

    // 使用参数化查询避免SQL注入，同时可根据实际需求指定查询字段
    const sql = `select u_id, username, type, phone,status,avatar from users where u_id =?`;
    const result = await exec(sql, [u_id]);
    if (result.length < 1) return res.output(ERROR_GETTING_USER_INFO.message, ERROR_GETTING_USER_INFO.code);

    // 假设这里不需要密码字段，若实际需要可根据情况处理
    // Object.defineProperty(result[0], 'password', {
    //     enumerable: false,
    // });

    res.output(SUCCESS_GETTING_INFO.message, SUCCESS_GETTING_INFO.code, result[0]);
}



// 获取指定用户相关权限
// 豆包生成


exports.getUserRoles = async (req, res) => {
    // 将变量名改为符合驼峰命名法的userId
    const { u_id } = req.body;
    // 使用参数化查询避免SQL注入，同时可根据实际需求指定查询字段

    const sql = `
    SELECT
        
        m.name AS menu_name,
        m.code AS 'key',
        m.node_type AS node_type,
        m.pid As pid,
        m.icon AS icon,
        m.sort AS sort,
        m.url AS link_url,
        m.level AS level,
        m.path AS path
    FROM
        role_menu rm
            JOIN
        menu m ON rm.menu_id = m.id
    WHERE
        rm.user_id = ?
    ORDER BY
        m.sort;
`

    const result = await exec(sql, [u_id]);
    if (result.length < 1) {
        // 这里可以进一步细化对查询结果为空情况的处理逻辑，目前先按原逻辑返回
        return res.output(ERROR_PERMISSION_INSUFFICIENT.message, ERROR_PERMISSION_INSUFFICIENT.code);
    }

    res.output(SUCCESS_GETTING_INFO.message, SUCCESS_GETTING_INFO.code, result);
}


// 获取权限表
exports.userRolesSheel = async (req, res) => {
    const sql = `select * from user_role`
    const result = await exec(sql)
    if (result.length < 1) return res.output("获取失败", -1)
    res.output("获取成功", 0, result)
}
// 获取用户列表
exports.getUserlist = async (req, res) => {
    // 获取当前页码，默认为1，如果前端没有传递页码参数
    let { currentPage = 1, pageSize = 50, username, phone, gender, status, type, register_time } = req.query;
    // 参与搜索功能
    
    // 计算查询的起始索引，用于实现分页

    const sql = `select u_id,username,type,phone,gender,status,avatar,update_time,register_time from users LIMIT ${currentPage - 1}, ${pageSize}`
    const result = await exec(sql)

    if (result.length < 1) return res.output("获取失败", -1)
    let rest = {
        total: result.length,
        data: result,
        totalPages: pageSize,
        currentPage,
    }
    res.output("获取成功", 0, rest)
}

// 新增用户列表
exports.addUser = async (req, res) => {
    let { phone, username,password,type } = req.body
    // 判断用户是否存在
    const sql = `select * from users where phone = '${phone}' or username='${username}'`
    const result = await exec(sql)
    if (result.length > 0) return res.output("用户已存在", -1)
    let sql1 = `insert into users (phone,username,password,type) values ('${phone}','${username}','${password}','${type}')`
    const result1 = await exec(sql1)
    if (result1.affectedRows < 1) return res.output("添加失败", -1)
    res.output("新增成功", 0)
}
// 删除用户
exports.deleteUser = async (req, res) => {
    let { u_id } = req.body
    // 将数据的status改为1,并且修改更新日期update_time字段
    const sql = `update users set status = 1 where u_id = '${u_id}'`
    const result = await exec(sql)
    if (result.affectedRows < 1) return res.output("删除失败", -1)
    res.output("删除成功", 0)
}


// 更新用户信息
exports.updateUserInfo = async (req, res) => {
    let   = req.body
    let dat = ''
    dat = formatToJson({ datas, filterItem: ['u_id'] })
    let { u_id } = req.body
    let sql = `update users set ${dat},update_time='${moment().format("YYYY-MM-DD HH:mm:ss")}' where u_id = '${u_id}'`
    const result = await exec(sql, dat)
    if (result.affectedRows == 1) {
        res.output("更新成功", 0)
    }
}


// 小程序
exports.wxLogin = async (req, res) => {
    let params = req.body
    let { code, encryptedData, iv, type, userInfo } = params
    let { avatarUrl, nickName } = userInfo
    //请求获取openid
    let url =
        "https://api.weixin.qq.com/sns/jscode2session?grant_type=" +
        wxUse.grant_type +
        "&appid=" +
        WECHAT_APPID +
        "&secret=" +
        WECHAT_SECRER +
        "&js_code=" +
        code;

    request(url, async (err, response, body) => {
        if (!err && response.statusCode == 200) {
            let _data = JSON.parse(body)
            _data.code = code
            _data.session_key = ""
            const user = { code: code }
            const wxToken = jwt.sign(user, setTokenOptions.jwtSecretKey, { expiresIn: setTokenOptions.expiresIn })
            // 定义sql 语句,查询当前用户是否存在(openid)
            const sql = "select * from users where user_id= ?"
            let result = await exec(sql, [_data.openid])

            if (result.length == 0) {
                const u_id = createUID()
                // 用户不存在,插入用户
                const sql1 = "insert into users (u_id,avatar,nick_name,user_id,register_time,type) values (?,?,?,?,?,?)"
                let ret = await exec(sql1, [u_id, avatarUrl, nickName, _data.openid, moment().format("YYYY-MM-DD HH:mm:ss"), type])
                if (ret.affectedRows != 1) return res.output("授权失败,请重试", -1)
                res.output("授权成功", 0, { token: wxToken, openid: _data.openid, nick_name: nickName, avatarUrl, u_id })
            } else {
                // 用户存在,更新用户信息
                const sql1 = `update users set ? where user_id = '${_data.openid}'`
                let ret = await exec(sql1, [{ nick_name: nickName, avatar: avatarUrl }])
                if (ret.affectedRows != 1) return res.output("授权失败,请重试", -1)
                let msg = {
                    token: wxToken,
                    openid: _data.openid,
                    nick_name: nickName,
                    avatarUrl,
                    phone: result[0].phone,
                    gender: result[0].gender,
                    u_id: result[0].u_id,
                }
                res.output("授权成功", 0, msg)
            }
        }
    })
}